﻿<script setup lang="ts" name="CropperAvatar">
import { CSSProperties } from 'vue'
import { successMessage } from '@/utils/message'
import { transformI18n } from '@/plugins/i18n'

const props = defineProps({
  width: {
    type: [String, Number],
    default: '200px'
  },
  value: { type: String },
  showBtn: { type: Boolean, default: true },
  btnText: { type: String, default: '' }
})

const emit = defineEmits(['update:value', 'change'])

const getWidth = computed(() => `${props.width}`.replace(/px/, '') + 'px')

const getIconWidth = computed(() => parseInt(`${props.width}`.replace(/px/, '')) / 2 + 'px')

const getStyle = computed((): CSSProperties => ({ width: unref(getWidth) }))

const getImageWrapperStyle = computed(
  (): CSSProperties => ({ width: unref(getWidth), height: unref(getWidth) })
)
const sourceValue = ref(props.value || '')

watchEffect(() => {
  sourceValue.value = props.value || ''
})

watch(
  () => sourceValue.value,
  (v: string) => {
    emit('update:value', v)
  }
)
const handleUploadSuccess = ({ source, data }) => {
  sourceValue.value = source
  emit('change', source)
  successMessage(transformI18n('successes.头像上传成功！', true))
}

const cropperModalRef = ref(null)
const openCropperModalDialog = () => {
  const cropperModalRefDom = unref(cropperModalRef)
  if (!cropperModalRefDom) return
  cropperModalRefDom.handleOpenDialog()
}
</script>

<template>
  <div class="cropper-avatar" :style="getStyle">
    <div class="cropper-image-wrapper" :style="getImageWrapperStyle" @click="openCropperModalDialog">
      <div class="cropper-image-mask" :style="getImageWrapperStyle">
        <svg-icon icon="ad:cloud-upload-outlined" :size="getIconWidth" :style="getImageWrapperStyle" color="#d6d6d6"></svg-icon>
      </div>
      <img :src="sourceValue" v-if="sourceValue" alt="avatar" />
    </div>
    <el-button class="cropper-upload-btn" v-if="showBtn" @click="openCropperModalDialog">{{ btnText ? btnText : $t('buttons.buttonCropperSelectImage') }}</el-button>
    <CropperModal ref="cropperModalRef" :src="sourceValue" @uploadSuccess="handleUploadSuccess"></CropperModal>
  </div>
</template>

<style scoped lang="scss">
.cropper-avatar{
  display: inline-block;
  text-align: center;

  .cropper-image-wrapper{
    overflow: hidden;
    background-color: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 50%;
    cursor: pointer;

    img{
      width: 100%;
    }
  }

  .cropper-image-mask{
    position: absolute;
    width: inherit;
    height: inherit;
    background: rgba(0, 0, 0, 0.4);
    border: inherit;
    border-radius: inherit;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.4s;

    :deep(svg){
      margin: auto;
    }

    &:hover{
      opacity: 1;
    }
  }

  .cropper-upload-btn{
    margin: 10px auto;
  }
}
</style>
